#include <QDebug>

#include "parameterspageparser.h"
#include "utils.h"
#include "constants.h"

namespace Jcr
{
class ParametersPageParserPrivate
{
public:
    QList<std::string> data;

    void getTrElementText(GumboNode* node);

};

void ParametersPageParserPrivate::getTrElementText(GumboNode* node)
{
    if (node->v.element.tag != GUMBO_TAG_TR)
        return;

    GumboVector* children = &node->v.element.children;
    int childCount = children->length;
    for (auto i = 0; i < childCount; ++i) {
        GumboNode* child = static_cast<GumboNode*>(children->data[i]);
        if (child->v.element.tag == GUMBO_TAG_TD) {
            std::string text = Jcr::GumboUtils::getNodeText(child);
            GumboAttribute* attr = gumbo_get_attribute(&child->v.element.attributes, "class");
            if (attr && (strcasecmp(attr->value, "bg5") == 0 ||
                strcasecmp(attr->value, "bg6") == 0 ||
                strcasecmp(attr->value, "bg3") == 0)) {
                if (text.empty())
                    continue;
                data << text;
            } else {
                data << (text.empty() ? "N/A" : text);
            }
        }
    }
}

ParametersPageParser::ParametersPageParser(QObject* parent) : ModelPageParser(parent)
{
    d_ptr = new ParametersPageParserPrivate;
    setUrl(Jcr::Utils::modelParametersUrl(QUrl(Jcr::TESTMODELPAGE2)));
}

ParametersPageParser::~ParametersPageParser()
{
    delete d_ptr;
}


const QList<std::string>& ParametersPageParser::parameters() const
{
    return d_ptr->data;
}

void ParametersPageParser::processNode(GumboNode *node)
{
    if (node->v.element.tag == GUMBO_TAG_TBODY) {
        GumboVector* children = &node->v.element.children;
        if (children->length > 2) {
            for (unsigned int i = 0; i < children->length; ++i) {
                GumboNode* subNode = static_cast<GumboNode*>(children->data[i]);
                d_ptr->getTrElementText(subNode);
            }
        }
    }
}

void ParametersPageParser::finalize()
{
//    foreach (auto d, d_ptr->data)
//        qDebug() << d.c_str();
    emit finished();
}

}
